<!--
* description: 备件销售出库
* author: ligy
* createdDate: 2021-3-4
-->

<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :stripe="false"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
      :dynamic-api-style="'restful'"
    >
      <template #StorageAndWarehouse="scope">
        <el-select
          v-model="scope.row['StorageAndWarehouse']"
          placeholder="请选择"
          @visible-change="visChange($event, scope.row, scope.col)"
          @change="valChange($event, scope.row, scope.col)"
        >
          <el-option
            v-for="item in scope.row['options'] || []"
            :key="item.warehouseId"
            :label="item.warehouseName"
            :value="item.warehouseId"
          />
        </el-select>
      </template>
      <template #outStoreQty="scope">
        <el-input-number
          :key="'oqty' + scope.$index"
          v-model="scope.row['outStoreQty']"
          :step="1"
          :min="0"
          :max="scope.row['saleQty']"
          step-strictly
        />
        <!--          @change="inStoreQtyChange($event, scope.row)"-->
      </template>
    </one-table-template>

    <edit
    :dynamic-edit-row-data="editRowData"
    ref="editDetails"   
  />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/pa/apiBranchWarehouse'
import request from '@/utils/request'
import Vue from 'vue'

export default {
  name: 'SparePartsSoldOut',

  components: {
    OneTableTemplate,
    Edit: () => import('./saleDeliveryEdit.vue')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editRowData: {},
      selectiondata: [],
      editPopupsVisible:false,
      // 网格查询API配置对象
      apiConfig: api.querySaleDeliveryInfo,

      callbackObj: {
        // 手动勾选时
        // onCheckSelect: (selection, row) => {
        //   this.selectiondata = selection
        // },
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectiondata = selection
        }
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '销售单号：',
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
            // {
            //   compKey: 'compKey2',
            //   labelName: '客户性质：',
            //   codeField: 'customerType',
            //   component: () => import('@/components/org/LookupValue'),
            //   oFields: 'statusId,statusText',
            //   options: [
            //     { statusId: '0', statusText: '一般客户' },
            //     { statusId: '2', statusText: '加盟店' }
            //   ],
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: true,
            //   span: 6
            // },
            {
              compKey: 'compKey3',
              labelName: '客户名称：',
              codeField: 'customerName',
              component: () => import('@/components/org/commonInput'),
              type: 'dropdownList',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey4',
              labelName: '销售类型：',
              codeField: 'saleType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '0', statusText: '呆滞件销售' },
                { statusId: '2', statusText: '常规销售' }
              ],
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey5',
              labelName: '制单日期：',
              codeField: 'beginDate,endDate',
              component: () =>
                import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: false,
              span: 6
            },
            {
              compKey: 'compKey6',
              labelName: '制单人：',
              codeField: 'empName',
              component: () => import('@/components/org/commonInput'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              span: 6
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'isRetrospect',
              label: '是否追溯件',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrId',
              label: '网点ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'partId',
              label: '备件ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'warehouseId',
              label: '仓库ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'saleOrderCode',
              label: '销售单号',
              isComponent: true,
              width: 165,
              comps: [
                {
                  compKey: 'propKey1',
                  codeField: 'saleOrderCode',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => {
                    var saleOrderCode = this.$utils.deepCopy(this.$refs['multipleTable'].list[index]).saleOrderCode
                    this.$refs['editDetails'].open(saleOrderCode)
                    this.$refs['editDetails'].dialogVisible = true 
                  }
                }
              ]
            },
            {
              prop: 'customerTypeCn',
              label: '客户性质'
            },
            {
              prop: 'saleTypeCn',
              label: '销售类型'
            },
            {
              prop: 'customerName',
              label: '客户名称'
            },
            {
              prop: 'customerPhone',
              label: '联系电话',
              width: 100
            },            
            {
              prop: 'empName',
              label: '制单人'
            },
            {
              prop: 'createdDate',
              label: '制单时间',
              width: '150px'
            }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(
        this,
        {
          saleOrderCode: '',
          customerName: '',
          saleType: '',
          beginDate: '',
          endDate: '',
          empName: '',
          partNo: '',
          partName: '',
          isOtherSale:'1'
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      wareHouseOptions: []
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
    // 或取仓库数据
    // this.loadWarehouseData()
  },

  methods: {
    valChange(val, row, col) {
      const target = row['options'].find(opt => opt.warehouseId === val)
      this.$set(row, 'warehouseInfo', target)
      this.$set(row, 'usableStockQty', target['usableStockQty'])
    },
    visChange(isOpen, row, col) {
      if (!isOpen) return
      this.loadWarehouseData(row)
    },
    loadWarehouseData(row) {
      this.$requestAPI({
        apiUrl: '/mp/e3sh/spareparts/nodestorehouse/sparePartsSoldOutService/findStorageAndWarehouse.do',
        variables: { partId: row['partId'], partNo: row['partNo'] }
      }).then(res => {
        if (res.result === '1') {
          this.$set(row, 'options', res.rows)
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    delivery() {
      // 校验有没有选择仓库
      let isValid = true
      this.selectiondata.every(row => {
        if (!('warehouseInfo' in row)) {
          isValid = false
          return false
        }
        return true
      })
      if (!isValid) return this.$message('请先选择仓库！')
      if (this.selectiondata.length > 0) {
        request({
          url: api.outOfStock.APIUrl,
          method: 'post',
          data: this.selectiondata
        }).then((res) => {
          if (res.result == '1') {
            this.$message.success(res.msg)
            this.queryTable(1)
          } else {
            this.$message.warning(res.msg)
          }
        })
      } else {
        this.$message.warning('请选择出库数据')
      }
    }
  }
}
</script>
